#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Unity MCP 笔记本电脑网格生成器
使用Python生成笔记本电脑的几何体数据，输出为Unity兼容的OBJ格式
"""

import math
import os

def create_box_vertices(width, height, depth, center=(0, 0, 0)):
    """创建立方体顶点"""
    cx, cy, cz = center
    w, h, d = width/2, height/2, depth/2
    
    vertices = [
        # 底面 (y = cy - h)
        (cx - w, cy - h, cz - d),  # 0
        (cx + w, cy - h, cz - d),  # 1
        (cx + w, cy - h, cz + d),  # 2
        (cx - w, cy - h, cz + d),  # 3
        # 顶面 (y = cy + h)
        (cx - w, cy + h, cz - d),  # 4
        (cx + w, cy + h, cz - d),  # 5
        (cx + w, cy + h, cz + d),  # 6
        (cx - w, cy + h, cz + d),  # 7
    ]
    return vertices

def create_box_faces():
    """创建立方体面（OBJ格式使用1开始的索引）"""
    faces = [
        # 底面 (y-)
        (1, 2, 3), (1, 3, 4),
        # 顶面 (y+)
        (5, 7, 6), (5, 8, 7),
        # 前面 (z-)
        (1, 5, 6), (1, 6, 2),
        # 后面 (z+)
        (4, 3, 7), (4, 7, 8),
        # 左面 (x-)
        (1, 4, 8), (1, 8, 5),
        # 右面 (x+)
        (2, 6, 7), (2, 7, 3),
    ]
    return faces

def create_plane_vertices(width, height, center=(0, 0, 0), normal=(0, 1, 0)):
    """创建平面顶点"""
    cx, cy, cz = center
    w, h = width/2, height/2
    
    if normal == (0, 1, 0):  # XZ 平面 (Y up)
        vertices = [
            (cx - w, cy, cz - h),
            (cx + w, cy, cz - h),
            (cx + w, cy, cz + h),
            (cx - w, cy, cz + h),
        ]
    elif normal == (0, 0, 1):  # XY 平面 (Z forward)
        vertices = [
            (cx - w, cy - h, cz),
            (cx + w, cy - h, cz),
            (cx + w, cy + h, cz),
            (cx - w, cy + h, cz),
        ]
    else:
        vertices = [
            (cx - w, cy - h, cz),
            (cx + w, cy - h, cz),
            (cx + w, cy + h, cz),
            (cx - w, cy + h, cz),
        ]
    
    return vertices

def create_plane_faces():
    """创建平面面"""
    return [(1, 2, 3), (1, 3, 4)]

def generate_keyboard_keys(keyboard_center, keyboard_width, keyboard_depth, key_size=0.02):
    """生成键盘按键"""
    vertices = []
    faces = []
    current_vertex_index = 1
    
    cx, cy, cz = keyboard_center
    
    # 键盘布局参数
    rows = 5
    cols = 14
    key_spacing = 0.025
    row_spacing = 0.025
    
    start_x = cx - (cols - 1) * key_spacing / 2
    start_z = cz - (rows - 1) * row_spacing / 2
    
    for row in range(rows):
        for col in range(cols):
            # 跳过一些位置来模拟真实键盘布局
            if row == 0 and col > 11:  # 功能键行较短
                continue
            if row == 4 and (col < 2 or col > 11):  # 空格键行
                continue
                
            key_x = start_x + col * key_spacing
            key_z = start_z + row * row_spacing
            key_y = cy + 0.001  # 稍微高于键盘表面
            
            # 为空格键创建更宽的按键
            if row == 4 and 4 <= col <= 9:  # 空格键位置
                if col == 4:  # 只在空格键开始位置创建一个大按键
                    key_width = key_spacing * 6
                    key_vertices = create_box_vertices(key_width, key_size/2, key_size, (key_x + key_spacing*2.5, key_y, key_z))
                else:
                    continue
            else:
                key_vertices = create_box_vertices(key_size, key_size/2, key_size, (key_x, key_y, key_z))
            
            # 添加顶点
            for vertex in key_vertices:
                vertices.append(vertex)
            
            # 添加面（调整索引）
            key_faces = create_box_faces()
            for face in key_faces:
                adjusted_face = tuple(current_vertex_index + i - 1 for i in face)
                faces.append(adjusted_face)
            
            current_vertex_index += len(key_vertices)
    
    return vertices, faces

def write_obj_file(filename, vertices, faces, normals=None, uvs=None):
    """将几何体数据写入OBJ文件"""
    print(f"正在生成 OBJ 文件: {filename}")
    
    with open(filename, 'w', encoding='utf-8') as f:
        f.write(f"# 笔记本电脑网格 - {os.path.basename(filename)}\n")
        f.write("# Generated by Unity MCP Python Runner\n\n")
        
        # 写入顶点
        for vertex in vertices:
            f.write(f"v {vertex[0]:.6f} {vertex[1]:.6f} {vertex[2]:.6f}\n")
        f.write("\n")
        
        # 写入法线（如果提供）
        if normals:
            for normal in normals:
                f.write(f"vn {normal[0]:.6f} {normal[1]:.6f} {normal[2]:.6f}\n")
            f.write("\n")
        
        # 写入UV坐标（如果提供）
        if uvs:
            for uv in uvs:
                f.write(f"vt {uv[0]:.6f} {uv[1]:.6f}\n")
            f.write("\n")
        
        # 写入面
        for face in faces:
            if len(face) == 3:
                f.write(f"f {face[0]} {face[1]} {face[2]}\n")
            elif len(face) == 4:
                f.write(f"f {face[0]} {face[1]} {face[2]} {face[3]}\n")
    
    print(f"OBJ 文件生成完成: {filename}")

def create_laptop_mesh():
    """创建笔记本电脑网格"""
    print("开始生成笔记本电脑网格...")
    
    # 确保输出目录存在
    assets_dir = "Assets/Meshes"
    if not os.path.exists(assets_dir):
        os.makedirs(assets_dir)
        print(f"创建目录: {assets_dir}")
    
    # 笔记本电脑组件尺寸参数
    laptop_width = 0.35
    laptop_depth = 0.25
    base_height = 0.02
    screen_height = 0.02
    screen_lift = 0.15  # 屏幕抬起高度
    
    # ======== 1. 创建笔记本底座 ========
    print("生成笔记本底座...")
    base_vertices = create_box_vertices(laptop_width, base_height, laptop_depth, (0, 0, 0))
    base_faces = create_box_faces()
    
    write_obj_file(f"{assets_dir}/LaptopBase.obj", base_vertices, base_faces)
    
    # ======== 2. 创建屏幕外壳 ========
    print("生成屏幕外壳...")
    screen_center = (0, screen_lift, laptop_depth/2 + 0.01)
    screen_vertices = create_box_vertices(laptop_width, screen_height, laptop_depth, screen_center)
    screen_faces = create_box_faces()
    
    write_obj_file(f"{assets_dir}/LaptopScreen.obj", screen_vertices, screen_faces)
    
    # ======== 3. 创建键盘区域 ========
    print("生成键盘...")
    keyboard_center = (0, base_height/2 + 0.001, -0.05)
    keyboard_vertices = create_box_vertices(laptop_width * 0.9, 0.005, laptop_depth * 0.7, keyboard_center)
    keyboard_faces = create_box_faces()
    
    # 生成按键
    key_vertices, key_faces = generate_keyboard_keys(keyboard_center, laptop_width * 0.9, laptop_depth * 0.7)
    
    # 合并键盘底板和按键
    all_keyboard_vertices = keyboard_vertices + key_vertices
    all_keyboard_faces = keyboard_faces.copy()
    
    # 调整按键面的索引
    vertex_offset = len(keyboard_vertices)
    for face in key_faces:
        adjusted_face = tuple(i + vertex_offset for i in face)
        all_keyboard_faces.append(adjusted_face)
    
    write_obj_file(f"{assets_dir}/LaptopKeyboard.obj", all_keyboard_vertices, all_keyboard_faces)
    
    # ======== 4. 创建屏幕显示面板 ========
    print("生成屏幕显示面板...")
    panel_center = (0, screen_lift, laptop_depth/2 + screen_height/2 + 0.001)
    panel_vertices = create_plane_vertices(laptop_width * 0.85, laptop_depth * 0.85, panel_center, (0, 0, 1))
    panel_faces = create_plane_faces()
    
    write_obj_file(f"{assets_dir}/LaptopScreenPanel.obj", panel_vertices, panel_faces)
    
    # ======== 5. 创建触摸板 ========
    print("生成触摸板...")
    touchpad_center = (0, base_height/2 + 0.001, laptop_depth/4)
    touchpad_vertices = create_plane_vertices(0.15, 0.1, touchpad_center, (0, 1, 0))
    touchpad_faces = create_plane_faces()
    
    write_obj_file(f"{assets_dir}/LaptopTouchpad.obj", touchpad_vertices, touchpad_faces)
    
    # ======== 6. 创建完整笔记本网格 ========
    print("生成完整笔记本网格...")
    
    # 合并所有组件
    all_vertices = []
    all_faces = []
    current_index = 1
    
    # 添加底座
    all_vertices.extend(base_vertices)
    all_faces.extend(base_faces)
    current_index += len(base_vertices)
    
    # 添加屏幕
    all_vertices.extend(screen_vertices)
    for face in screen_faces:
        adjusted_face = tuple(i + current_index - 1 for i in face)
        all_faces.append(adjusted_face)
    current_index += len(screen_vertices)
    
    # 添加键盘（包括按键）
    all_vertices.extend(all_keyboard_vertices)
    for face in all_keyboard_faces:
        adjusted_face = tuple(i + current_index - 1 for i in face)
        all_faces.append(adjusted_face)
    current_index += len(all_keyboard_vertices)
    
    # 添加屏幕面板
    all_vertices.extend(panel_vertices)
    for face in panel_faces:
        adjusted_face = tuple(i + current_index - 1 for i in face)
        all_faces.append(adjusted_face)
    current_index += len(panel_vertices)
    
    # 添加触摸板
    all_vertices.extend(touchpad_vertices)
    for face in touchpad_faces:
        adjusted_face = tuple(i + current_index - 1 for i in face)
        all_faces.append(adjusted_face)
    
    # 写入完整网格
    write_obj_file(f"{assets_dir}/LaptopMesh.obj", all_vertices, all_faces)
    
    print(f"\n✅ 笔记本电脑网格生成完成！")
    print(f"📁 输出目录: {assets_dir}")
    print("🎮 现在可以将这些OBJ文件导入到Unity中使用")
    
    # 输出生成的文件列表
    generated_files = [
        "LaptopBase.obj",
        "LaptopScreen.obj", 
        "LaptopKeyboard.obj",
        "LaptopScreenPanel.obj",
        "LaptopTouchpad.obj",
        "LaptopMesh.obj"
    ]
    
    print("\n📋 生成的文件:")
    for file in generated_files:
        print(f"   • {file}")
    
    return generated_files

def generate_basic_texture_data():
    """生成基本纹理数据信息"""
    print("\n🎨 纹理建议:")
    print("   • 键盘纹理: 深灰色，带有按键标记")
    print("   • 屏幕纹理: 黑色或深蓝色背景")
    print("   • 机身纹理: 银灰色金属质感")
    print("   • 触摸板纹理: 光滑的深灰色表面")

if __name__ == "__main__":
    # 生成笔记本电脑网格
    generated_files = create_laptop_mesh()
    generate_basic_texture_data()
    
    print(f"\n🎯 下一步:")
    print("1. 使用Unity MCP将OBJ文件导入Unity")
    print("2. 为不同部件创建材质")
    print("3. 组装成完整的笔记本电脑预制体")

